package com.plentitude.easytrader.ui;

import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

import com.plentitude.easytrader.R;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Editable;
import android.text.InputFilter;
import android.text.Spanned;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.RadioButton;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;


/**
 * Page with application specific settings.
 * 
 * @author team@getstarted.com.ua
 */
public class SettingsActivity extends Activity implements OnCheckedChangeListener, OnSeekBarChangeListener {
	private String TAG = "SettingsActivity";
	private SharedPreferences settings;
	private EditText tradingFunds;
	private EditText maxRisk;
	private SeekBar actionDistance;
	private TextView edtActionDistance;
	private SeekBar reward;
	private TextView edtReward;
	private SeekBar priceUpdates;
	private TextView edtPriceUpdates;
	private CheckBox cbPriceUpdates;
	private SeekBar synchronization;
	private TextView edtSynchronization;
	private CheckBox cbSynchronization;
	private CheckBox cbYahooUK;
	private CheckBox cbYahooUS;
	private CheckBox cbSynchFull;
	private CheckBox cbSynchPartial;
	private CheckBox cbSynchServer;
	private RadioButton rbIdle;
	private ProgressBar pbSynchNow;
	private TextView lastSynch;
	private int account;
    
	
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
        setContentView(R.layout.activity_settings);
        
        settings = getSharedPreferences(Keys.KEY, 0);
        
        tradingFunds = (EditText) findViewById(R.id.edtTradingFunds);
        tradingFunds.setRawInputType(Configuration.KEYBOARD_12KEY);
        tradingFunds.addTextChangedListener(new TradingFundsFilter());
        maxRisk = (EditText) findViewById(R.id.edtMaxRisk);
        maxRisk.setRawInputType(Configuration.KEYBOARD_12KEY);
        maxRisk.setFilters(new InputFilter[]{new MaxRiskFilter("1", "100")});
        actionDistance = (SeekBar) findViewById(R.id.pbActionDistance);
        actionDistance.setOnSeekBarChangeListener(this);
        edtActionDistance = (TextView) findViewById(R.id.edtActionDistance);
        reward = (SeekBar) findViewById(R.id.pbReward);
        reward.setOnSeekBarChangeListener(this);
        edtReward = (TextView) findViewById(R.id.edtReward);
        priceUpdates = (SeekBar) findViewById(R.id.pbPriceUpdates);
        priceUpdates.setOnSeekBarChangeListener(this);
        edtPriceUpdates = (TextView) findViewById(R.id.edtPriceUpdates);
        cbPriceUpdates = (CheckBox) findViewById(R.id.cbPriceUpdates);
        synchronization = (SeekBar) findViewById(R.id.pbSynchronization);
        synchronization.setOnSeekBarChangeListener(this);
        edtSynchronization = (TextView) findViewById(R.id.edtSynchronization);
        cbSynchronization = (CheckBox) findViewById(R.id.cbSynchronization);
        cbYahooUK = (CheckBox) findViewById(R.id.cbYahooUK);
        cbYahooUK.setOnCheckedChangeListener(this);
        cbYahooUS = (CheckBox) findViewById(R.id.cbYahooUS);
        cbYahooUS.setOnCheckedChangeListener(this);
        cbSynchFull = (CheckBox) findViewById(R.id.cbSynchFull);
        cbSynchFull.setOnCheckedChangeListener(this);
        cbSynchPartial = (CheckBox) findViewById(R.id.cbSynchPartial);
        cbSynchPartial.setOnCheckedChangeListener(this);
        cbSynchServer = (CheckBox) findViewById(R.id.cbSynchServer);
        cbSynchServer.setOnCheckedChangeListener(this);
        rbIdle = (RadioButton) findViewById(R.id.rbIdle);
        pbSynchNow = (ProgressBar) findViewById(R.id.pbSynchNow);
        lastSynch = (TextView) findViewById(R.id.edtLastSynch);
        
        readSettings();
        getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.title);
    }

    /** Handle "synchronize now" action. */
    public void onSynchNow(View v) {
    	new SynchTask().execute();
    }
    
    class SynchTask extends AsyncTask<String, String, Boolean>{
    	@Override
    	protected void onPreExecute() {
        	pbSynchNow.setMax(1000);
    		rbIdle.setChecked(true);
    	}
    	
    	@Override
    	protected Boolean doInBackground(String... params) {
        	for(int i=0; i<1000; i++) {
        		pbSynchNow.incrementProgressBy(100);
        	}
        	return true;
    	}

    	@Override
    	protected void onPostExecute(Boolean result) {
        	rbIdle.setChecked(false);
        	pbSynchNow.setProgress(0);
        	SimpleDateFormat sdf = new SimpleDateFormat("d MMM yyyy HH:mm:ss");
        	String timestamp = sdf.format(new Date()); 
        	lastSynch.setText(timestamp);
        	SharedPreferences.Editor editor = settings.edit();
        	editor.putString(Keys.set_lastSynch, timestamp);
        	editor.commit();
    	}
    }
    
    /** Handle "settings restore" action. */
    public void onSettingsRestore(View v) {
    	SharedPreferences.Editor editor = settings.edit();
    	
    	editor.putString(Keys.set_tradingFunds, Keys.set_tradingFunds_default);
        editor.putInt(Keys.set_maxRisk, Keys.set_maxRisk_default);
        editor.putInt(Keys.set_actionDistance, Keys.set_actionDistance_default);
        editor.putInt(Keys.set_reward, Keys.set_reward_default);
        editor.putInt(Keys.set_priceUpdates, Keys.set_priceUpdates_default);
        editor.putBoolean(Keys.set_cbPriceUpdates, Keys.set_cbPriceUpdates_default);
        editor.putInt(Keys.set_synchronization, Keys.set_synchronization_default);
        editor.putBoolean(Keys.set_cbSynchronization, Keys.set_cbSynchronization_default);
        editor.putBoolean(Keys.set_cbYahooUK, Keys.set_cbYahooUK_default);
        editor.putBoolean(Keys.set_cbYahooUS, Keys.set_cbYahooUS_default);
        editor.putBoolean(Keys.set_cbSynchFull, Keys.set_cbSynchFull_default);
        editor.putBoolean(Keys.set_cbSynchPartial, Keys.set_cbSynchPartial_default);
        editor.putBoolean(Keys.set_cbSynchServer, Keys.set_cbSynchServer_default);
        editor.putInt(Keys.set_account, Keys.set_account_default);
        
        editor.commit();
        readSettings();
    }
    
    /** Handle "account types" action. */
    public void onAccountType(View v) {
    	final AlertDialog.Builder builder = new AlertDialog.Builder(this);
    	CharSequence[] items = new CharSequence[] {getString(R.string.ac_spread_betting), getString(R.string.ac_cfd), getString(R.string.ac_ordinary_shares)}; 
    	builder.setSingleChoiceItems(items, account, new DialogInterface.OnClickListener(){
             public void onClick(DialogInterface dialogInterface, int item) {
            	account = item; 
                dialogInterface.dismiss();
             }
         });
    	 builder.create().show();
    }

    @Override
    public void onBackPressed() {
    	Bundle extras = getIntent().getExtras();
    	if(extras != null && extras.getBoolean(Keys.FIRST_RUN)) {
	    	// Start welcome activity
	    	final Intent intent = new Intent(SettingsActivity.this, HomeActivity.class);
	        startActivity(intent);
    	}
    	finish();
    }
    
    /** Handle "settings save" action. */
    public void onSettingsSave(View v) {
    	saveSettings();

    	Bundle extras = getIntent().getExtras();
    	if(extras != null && extras.getBoolean(Keys.FIRST_RUN)) {
	    	// Start settings activity
	    	final Intent intent = new Intent(SettingsActivity.this, HomeActivity.class);
	        startActivity(intent);
    	}
    	
    	finish();
    }
    
	@Override
    protected void onDestroy() {
    	super.onDestroy();
    	settings = null;
        tradingFunds = null;
        maxRisk = null;
        actionDistance = null;
        reward = null;
        priceUpdates = null;
        cbPriceUpdates = null;
        synchronization = null;
        cbSynchronization = null;
        cbYahooUK = null;
        cbYahooUS = null;
        cbSynchFull = null;
        cbSynchPartial = null;
        cbSynchServer = null;
        rbIdle = null;
        pbSynchNow = null;
        lastSynch = null;

	}
    
	@Override
	public void onCheckedChanged(CompoundButton button, boolean checked) {
		if(checked) {
			if(cbSynchFull.equals(button)) {
				cbSynchPartial.setChecked(false);
				cbSynchServer.setChecked(false);
			} else if(cbSynchPartial.equals(button)) {
				cbSynchFull.setChecked(false);
				cbSynchServer.setChecked(false);
			} else if(cbSynchServer.equals(button)) {
				cbSynchFull.setChecked(false);
				cbSynchPartial.setChecked(false);
			} else if(cbYahooUK.equals(button)) {
				cbYahooUS.setChecked(false);
			} else if(cbYahooUS.equals(button)) {
				cbYahooUK.setChecked(false);
			}
		}
		
	}
	
	@Override
	public void onProgressChanged(SeekBar seekbar, int position, boolean arg2) {
		if(actionDistance.equals(seekbar)) {
			edtActionDistance.setText(""+position);
		} else if(reward.equals(seekbar)) {
			edtReward.setText(""+position);
		} else if(priceUpdates.equals(seekbar)) {
			switch(position) {
				case 0: edtPriceUpdates.setText("1");
					break;
				case 1: edtPriceUpdates.setText("5");
					break;
				case 2: edtPriceUpdates.setText("15");
					break;
				case 3: edtPriceUpdates.setText("30");
					break;
				case 4: edtPriceUpdates.setText("60");
					break;
			}
		} else if(synchronization.equals(seekbar)) {
			switch(position) {
				case 0: edtSynchronization.setText("1");
					break;
				case 1: edtSynchronization.setText("2");
					break;
				case 2: edtSynchronization.setText("3");
					break;
				case 3: edtSynchronization.setText("4");
					break;
				case 4: edtSynchronization.setText("5");
					break;
				case 5: edtSynchronization.setText("6");
					break;
			}
		}
		
	}

	@Override
	public void onStartTrackingTouch(SeekBar arg0) {
	}

	@Override
	public void onStopTrackingTouch(SeekBar arg0) {
	}
	
	
	// PRIVATE METHODS
	private void readSettings() {
		tradingFunds.setText(settings.getString(Keys.set_tradingFunds, Keys.set_tradingFunds_default));
        maxRisk.setText(""+settings.getInt(Keys.set_maxRisk, Keys.set_maxRisk_default));
        actionDistance.setProgress(settings.getInt(Keys.set_actionDistance, Keys.set_actionDistance_default));
        reward.setProgress(settings.getInt(Keys.set_reward, Keys.set_reward_default));
        priceUpdates.setProgress(settings.getInt(Keys.set_priceUpdates, Keys.set_priceUpdates_default));
        cbPriceUpdates.setChecked(settings.getBoolean(Keys.set_cbPriceUpdates, Keys.set_cbPriceUpdates_default));
        synchronization.setProgress(settings.getInt(Keys.set_synchronization, Keys.set_synchronization_default));
        cbSynchronization.setChecked(settings.getBoolean(Keys.set_cbSynchronization, Keys.set_cbSynchronization_default));
        cbYahooUK.setChecked(settings.getBoolean(Keys.set_cbYahooUK, Keys.set_cbYahooUK_default));
        cbYahooUS.setChecked(settings.getBoolean(Keys.set_cbYahooUS, Keys.set_cbYahooUS_default));
        cbSynchFull.setChecked(settings.getBoolean(Keys.set_cbSynchFull, Keys.set_cbSynchFull_default));
        cbSynchPartial.setChecked(settings.getBoolean(Keys.set_cbSynchPartial, Keys.set_cbSynchPartial_default));
        cbSynchServer.setChecked(settings.getBoolean(Keys.set_cbSynchServer, Keys.set_cbSynchServer_default));
        lastSynch.setText(settings.getString(Keys.set_lastSynch, ""));
        account = settings.getInt(Keys.set_account, Keys.set_account_default);
	}
	
	private void saveSettings() {
    	SharedPreferences.Editor editor = settings.edit();
    	
    	editor.putString(Keys.set_tradingFunds, tradingFunds.getText().toString());
        editor.putInt(Keys.set_maxRisk, Integer.parseInt(maxRisk.getText().toString()));
        editor.putInt(Keys.set_actionDistance, actionDistance.getProgress());
        editor.putInt(Keys.set_reward, reward.getProgress());
        editor.putInt(Keys.set_priceUpdates, priceUpdates.getProgress());
        editor.putBoolean(Keys.set_cbPriceUpdates, cbPriceUpdates.isChecked());
        editor.putInt(Keys.set_synchronization, synchronization.getProgress());
        editor.putBoolean(Keys.set_cbSynchronization, cbSynchronization.isChecked());
        editor.putBoolean(Keys.set_cbYahooUK, cbYahooUK.isChecked());
        editor.putBoolean(Keys.set_cbYahooUS, cbYahooUS.isChecked());
        editor.putBoolean(Keys.set_cbSynchFull, cbSynchFull.isChecked());
        editor.putBoolean(Keys.set_cbSynchPartial, cbSynchPartial.isChecked());
        editor.putBoolean(Keys.set_cbSynchServer, cbSynchServer.isChecked());
        editor.putInt(Keys.set_account, account);

        editor.commit();
	}
	
	class MaxRiskFilter implements InputFilter {
		 
		private int min, max;
	 
		public MaxRiskFilter(int min, int max) {
			this.min = min;
			this.max = max;
		}
	 
		public MaxRiskFilter(String min, String max) {
			this.min = Integer.parseInt(min);
			this.max = Integer.parseInt(max);
		}
	 
		@Override
		public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {	
			try {
				int input = Integer.parseInt(dest.toString() + source.toString());
				if (isInRange(min, max, input))
					return null;
			} catch (NumberFormatException nfe) { }		
			return "";
		}
	 
		private boolean isInRange(int a, int b, int c) {
			return b > a ? c >= a && c <= b : c >= b && c <= a;
		}
	}
	
	class TradingFundsFilter implements TextWatcher {
        private String current;

        @Override
        public void afterTextChanged(Editable arg0) {
        }
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }
        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
        	if(!s.toString().equals(current)){
        		String formatted = "";
        		try {
        		   String cSymbol = NumberFormat.getCurrencyInstance().getCurrency().getSymbol(); 
        		   String replaceable = String.format("[%s,.\\s]", cSymbol);
        		   String cleanString = s.toString().replaceAll(replaceable, "");
        		   if("".equals(cleanString)) cleanString = "0";
        		   double parsed = Double.parseDouble(cleanString);
        		   formatted = NumberFormat.getCurrencyInstance().format((parsed/100));
        	   } catch(Exception e) {
        		   Log.e(TAG, e.toString());
        	   }
    		   current = formatted;
    		   tradingFunds.setText(formatted);
    		   tradingFunds.setSelection(formatted.length());
       	    }
        }
    }
}
